package com.unittec.zk.provider.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

import com.unittec.zk.sdk.root.internal.exception.BusinessException;

/**
 * 校验工具类
 *
 * @author wuxinwei
 */
public class ValidationUtils {

    private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> ValidationResult validateEntity(T obj) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (set != null && set.size() != 0) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = new HashMap<String, String>();
            StringBuilder sb = new StringBuilder();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
                sb.append(cv.getMessage() + "  ");
            }
            result.setErrorMsg(errorMsg);
            result.setErrorMsgStr(sb.toString());
        }
        return result;
    }

    public static <T> boolean validateEntityStr(T obj) {
        if (null == obj) {
            throw new BusinessException("param is null");
        }
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (set != null && set.size() != 0) {
            StringBuilder sb = new StringBuilder();
            for (ConstraintViolation<T> cv : set) {
                sb.append(cv.getMessage()).append("  ");
            }
            throw new BusinessException(sb.toString());
        }
        return true;
    }

    public static <T> ValidationResult validateProperty(T obj, String propertyName) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
        if (set != null && set.size() != 0) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = new HashMap<String, String>();
            StringBuilder sb = new StringBuilder();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(propertyName, cv.getMessage());
                sb.append(cv.getMessage() + "  ");
            }
            result.setErrorMsg(errorMsg);
            result.setErrorMsgStr(sb.toString());
        }
        return result;
    }
}
